/**
 * 创建服务端程序完成图片的上传功能。
 * 点击选择图片进行图片选择，点击提交时，将本地选中图片上传到服务端程序所在目录的upload文件夹下。
 * 当访问localhost:8081/list时，将upload文件夹下的所有图片显示到页面
 */

const http = require("http");
const fs = require("fs");
const path = require("path");


http.createServer((req,res)=>{
    var urlObj = new URL(req.url, "http://localhost:8081/")
    // console.log(urlObj); //可以先输出对象看结构
    var pathName = urlObj.pathname;
    
    if(pathName =="/"){
        var fileContent = fs.readFileSync("./index.html");
        res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
        res.write(fileContent);
        res.end();
    }
    else if(pathName =="/upload" ){
        var str= ""
        req.setEncoding("binary")
        req.on("data",(chunk)=>{
            str += chunk;
        })
        req.on("end",()=>{
            console.log(str)
            var arr = str.split("\r\n");
            var imgArr = arr.slice(4,arr.length-2);
            var imgStr = imgArr.join("\r\n");
            var buf = Buffer.from(imgStr,"binary");
            var time = new Date().getTime(); //获得当前时间戳
            fs.writeFileSync(path.join(__dirname,"/upload/"+time+".png"),buf,{"encoding":"binary"})
        })
    }
    else if(pathName == "/list"){
        var fileContent = fs.readFileSync("./list.html");
        res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
        res.write(fileContent);
        res.end();
    }
    else if(pathName =="/getlist"){
        var uploadPath = path.join(__dirname,'/upload');
        var img = fs.readdirSync(uploadPath);
        res.writeHead(200,{'content-type':'text/plain'});
        res.write(JSON.stringify(img));
        res.end();
        
        
    }
    else if(pathName.indexOf('upload/')>=0){
        var imgObj = pathName.slice(-17); //图片的名字带后缀
        var postfix = imgObj.slice(-4); //图片的后缀
        
        var imgPath = path.join(__dirname,"/upload/"+imgObj);
        var imgBuffer = fs.readFileSync(imgPath);
        if(postfix == ".png"){
            res.writeHead(200,{'content-type':'image/png'});
            res.write(imgBuffer);
            res.end();
        }
        else if(postfix == ".jpg"){
            res.writeHead(200,{'content-type':'image/jpeg'});
            res.write(imgBuffer);
            res.end();
        }
        
    }
    
    
    
}).listen(8081);